package cn.practice.articlepractice.common.exception;

import cn.practice.articlepractice.common.response.JsonResult;
import cn.practice.articlepractice.common.response.StatusCode;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getFieldError().getDefaultMessage();
        log.error("参数校验失败:{}", message);
        return new JsonResult(StatusCode.OPERATION_FAILED, message);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.error("参数校验失败", e.getMessage());
        return JsonResult.exception(e.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e) {
        log.error("系统异常", e.getMessage());
        return JsonResult.exception(e.getMessage());
    }
}
